<template>
    <div id="VIP_index" class="all">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item>购物结账</el-breadcrumb-item>
        </el-breadcrumb>

        <br>



        <!--表格数据-->
        <div class="table-container">
            <span style="margin-right: 91%;padding: 10px;"><b>商品列表</b></span>
            <el-divider class="custom-divider"></el-divider>
            <el-table :data="maindata" style="width: 100%" size="medium">
                <el-table-column prop="name" width="200" label="商品名称"></el-table-column>
                <el-table-column width="200" prop="intro" label="简介"></el-table-column>
                <el-table-column width="150" prop="price" label="单价/元"></el-table-column>
                <el-table-column width="150" prop="isvipCommodity" label="是否为积分商品">
                    <template slot-scope="scope">
                        {{ isVIP(scope.row.isvipCommodity) }}
                    </template>
                </el-table-column>
                <el-table-column width="150" prop="vipScore" label="积分"></el-table-column>
                <el-table-column label="支付方式" width="200">
                    <template slot-scope="scope">
                        <el-radio v-model="maindata[scope.$index].radio" label="0">金钱支付</el-radio>
                        <el-radio v-model="maindata[scope.$index].radio" label="1"
                            :disabled="maindata[scope.$index].isvipCommodity === 0">积分支付</el-radio>
                    </template>
                </el-table-column>
                <el-table-column label="是否购买" width="220" fixed="right">
                    <template slot-scope="scope">
                        <input type="checkbox" v-model="selectedRows[scope.$index]">
                    </template>
                </el-table-column>
            </el-table>
            <div class="dialog-footer" style="padding: 1%;">
                <el-button type="primary" style="font-size: 16px;padding:15px 20px;margin-left: 80%;"
                    @click="submitparchase(); getSelectedData();">结账</el-button>
            </div>
        </div>

    </div>
</template>
  
<script>
import axios from 'axios';
export default {
    data() {
        return {
            empId: "",
            cusId: "",
            username: "",
            password: "",
            totalPrice: 0,
            totalVipScore: 0,
            sellGoodsLists: [

            ],
            maindata: [
                {
                    commodityId: "1",
                    name: "保温杯",
                    price: "99",
                    intro: "暖暖的很贴心",
                    isvipCommodity: "1",
                    vipScore: "300",
                    radio: "1",
                },
                {
                    commodityId: "2",
                    name: "保温杯",
                    price: "99",
                    intro: "暖暖的很贴心",
                    isvipCommodity: "0",
                    vipScore: "300",
                    radio: "0",
                },
                {
                    commodityId: "3",
                    name: "保温杯",
                    price: "99",
                    intro: "暖暖的很贴心",
                    isvipCommodity: "1",
                    vipScore: "300",
                    radio: "1",
                },
                {
                    commodityId: "4",
                    name: "保温杯",
                    price: "99",
                    intro: "暖暖的很贴心",
                    isvipCommodity: "1",
                    vipScore: "300",
                    radio: "0",
                },
            ],
            selectedRows: [],
            selectedData: [],
            inputMessage: false,
            showMessage: false,
            updateMessage: false,

            formLabelWidth: '80px'
        };
    },
    methods: {
        getMaindata() {
            const url = "http://localhost:8080/sell";
            axios.get(url)
                .then((response) => {
                    console.log(response.data);
                    this.maindata = response.data.data.rows;
                    this.addRadioToData();
                })
                .catch((error) => {
                    console.error('Error in getMaindata request', error);
                });
        },
        created() {
            this.selectedRows = new Array(this.maindata.length).fill(false);

        },
        checkid() {
            if (this.empId == "" || this.empId == null)
                this.$router.push('/login');
        },

        isVIP(now) {
            let result = "是";
            if (now == 0)
                result = "否";
            return result;
        },
        init() {
            this.empId = localStorage.getItem('empId');
            this.cusId = localStorage.getItem('cusId');
            this.username = localStorage.getItem('username') || "";
            this.password = localStorage.getItem('password') || "";
        },

        submitparchase() {
            this.$confirm("此操作将结账当前所有商品, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                center: true,
            })
                .then(() => {
                    this.sellGoodsLists = this.maindata.filter((item, index) => this.selectedRows[index]);
                    console.log("被选中的数据：", this.sellGoodsLists);
                    this.calculateTotals();
                    this.$message({
                        type: "success",
                        message: "结账成功!",
                    });
                    this.inputData();
                }
                )
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消结账",
                    });
                });
        },
        inputData() {
            const url = "http://localhost:8080/sell";
            const dataToSend = {
                sellGoodsLists: this.sellGoodsLists,
                empId: this.empId,
                cusId: Math.floor(Math.random() * 2) + 1,
                totalPrice: this.totalPrice,
                totalvipScore: this.totalVipScore
            };
            console.log("被传输的数据：", dataToSend);
            axios.post(url, dataToSend
            ).then((response) => {
                console.log(response.data);
                this.inputDatap2(dataToSend);
            })
                .catch((error) => {
                    console.error('Error in inputData request', error);
                });
        },
        inputDatap2(dataToSend) {
            const url = "http://localhost:8080/selldetail"
            console.log("被传输的数据：", dataToSend);
            axios.post(url, dataToSend
            ).then((response) => {
                console.log(response.data);
                this.inputDatap3(dataToSend);
            })
                .catch((error) => {
                    console.error('Error in inputData request', error);
                });
        },
        inputDatap3(dataToSend) {
            const url = "http://localhost:8080/outchange"
            console.log("被传输的数据：", dataToSend);
            axios.put(url, dataToSend
            ).then((response) => {
                console.log(response.data);
            })
                .catch((error) => {
                    console.error('Error in inputData request', error);
                });
            this.selectedRows = [];
            this.selectedData = [];
        },
        addRadioToData() {
            // 在这个函数中为每个对象添加 radio 属性
            this.maindata.forEach(item => {
                this.$set(item, 'radio', '0'); // 设置默认值，你可以根据需要修改
            });
        },
        calculateTotals() {
            this.totalPrice = 0;
            this.totalVipScore = 0;

            this.sellGoodsLists.forEach(item => {
                if (item.radio === "0") {
                    this.totalPrice += parseFloat(item.price);
                } else if (item.radio === "1") {
                    this.totalVipScore += parseInt(item.vipScore);
                }
            });
        }

    },
    mounted() {
        this.init();
        this.checkid();
        this.getMaindata();

        this.created();
    },
};
</script>
  
<style>
.router-link-active {
    text-decoration: none;
}

.table-container {
    box-shadow: 0 0 4px 1px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .12);
}

.custom-divider {
    margin: 4px 0;
    /* 调整 el-divider 的间距 */
}

.custom-descriptions {
    padding-left: 10px;
    margin-bottom: 0;
}

.all {
    line-height: 30px;
}
</style>